package com.common.method;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;

public class CommonMethod2 {
	private ProgressDialog mDialog;
	Handler handler;
	private Context mContext;
	private String TAG = "CommonMethod2";

	public CommonMethod2(Context context) {
		this.mContext = context;
		handler = new Handler();
	}

	public void showProgressDialog() {
		if (mDialog == null) {
			mDialog = new ProgressDialog(mContext);
			mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// ���÷��ΪԲ�ν����
			mDialog.setMessage("���ڼ��� ����ȴ�...");
			mDialog.setIndeterminate(false);// ���ý�����Ƿ�Ϊ����ȷ
			mDialog.setCancelable(true);// ���ý�����Ƿ���԰��˻ؼ�ȡ��
			mDialog.setCanceledOnTouchOutside(false);
			mDialog.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss(DialogInterface dialog) {
					// TODO Auto-generated method stub
					mDialog = null;
				}
			});
			mDialog.show();

		}
	}

	public void closeProgressDialog() {
		if (mDialog != null) {
			mDialog.dismiss();
			mDialog = null;
		}
	}

	public Intent getFileIntent(File file) {
		// Uri uri = Uri.parse("http://m.ql18.com.cn/hpf10/1.pdf");
		Uri uri = Uri.fromFile(file);
		String type = getMIMEType(file);
		Log.i("tag", "type=" + type);
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setDataAndType(uri, type);
		return intent;
	}

	public void writeToSDCard(String fileName, InputStream input) {

		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			File directory = Environment.getExternalStorageDirectory();
			File file = new File(directory, fileName);
			// if(file.exists()){
			// Log.i("tag", "The file has already exists.");
			// return;
			// }
			try {
				FileOutputStream fos = new FileOutputStream(file);
				byte[] b = new byte[2048];
				int j = 0;
				while ((j = input.read(b)) != -1) {
					fos.write(b, 0, j);
				}
				fos.flush();
				fos.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			Log.i("tag", "NO SDCard.");
		}
	}

	public void downNewVersionUpdate(final String filename, final String url) {
		StringBuffer buffer = new StringBuffer();
		buffer.append(filename);
		Dialog dialog = new AlertDialog.Builder(mContext)
				.setTitle("�������")
				.setMessage((buffer).toString())
				.setPositiveButton("����", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

						mDialog = new ProgressDialog(mContext);
						mDialog.setTitle("��������");
						mDialog.setMessage("���Ժ�...");
						mDialog.setProgressStyle(mDialog.STYLE_SPINNER);
						mDialog.setCanceledOnTouchOutside(false);
						Log.i("filename", filename + "");
						downFile(url + "?" + System.currentTimeMillis(),
								filename);

					}
				})
				.setNegativeButton("ȡ��", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						((Activity) mContext).finish();
					}
				}).create();
		dialog.show();

	}

	protected void downFile(final String url, final String filename) {
		mDialog.show();
		new Thread() {
			public void run() {
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(url);
				Log.i(TAG, "downFile:" + url);
				HttpResponse response;
				try {
					response = client.execute(get);
					HttpEntity entity = response.getEntity();
					long length = entity.getContentLength();
					InputStream is = entity.getContent();
					FileOutputStream fileOutputStream = null;
					if (is != null) {

						File file = new File(
								Environment.getExternalStorageDirectory(),
								filename);
						Log.i(TAG, "Environment.getExternalStorageDirectory()"
								+ Environment.getExternalStorageDirectory());
						fileOutputStream = new FileOutputStream(file);
						byte[] buf = new byte[1024];
						int ch = -1;
						int count = 0;
						while ((ch = is.read(buf)) != -1) {
							fileOutputStream.write(buf, 0, ch);
							count += ch;
							if (length > 0) {
							}
						}
					}
					fileOutputStream.flush();
					if (fileOutputStream != null) {
						fileOutputStream.close();
					}
					Log.i(TAG, "-----------------�������--------------");

					// �Զ���װ
					down(filename);
				} catch (ClientProtocolException e) {
					Log.i(TAG, "ClientProtocolException" + e.getMessage());
				} catch (IOException e) {
					Log.i(TAG, "IOException" + e.getMessage());
				}
			}

		}.start();

	}

	void down(final String filename) {

		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				mDialog.cancel();
				update(filename);

			}
		});

	}

	public void update(final String filename) {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(Environment
				.getExternalStorageDirectory(), filename)),
				"application/vnd.android.package-archive");
		mContext.startActivity(intent);
		((Activity) mContext).finish();

	}

	public String getMIMEType(File f) {
		String type = "";
		String fName = f.getName();
		/* ȡ����չ�� */
		String end = fName
				.substring(fName.lastIndexOf(".") + 1, fName.length())
				.toLowerCase();

		/* ����չ������;���MimeType */
		if (end.equals("pdf")) {
			type = "application/pdf";//
		} else if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
				|| end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
			type = "audio/*";
		} else if (end.equals("3gp") || end.equals("mp4")) {
			type = "video/*";
		} else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
				|| end.equals("jpeg") || end.equals("bmp")) {
			type = "image/*";
		} else if (end.equals("apk")) {
			/* android.permission.INSTALL_PACKAGES */
			type = "application/vnd.android.package-archive";
		}
		// else if(end.equals("pptx")||end.equals("ppt")){
		// type = "application/vnd.ms-powerpoint";
		// }else if(end.equals("docx")||end.equals("doc")){
		// type = "application/vnd.ms-word";
		// }else if(end.equals("xlsx")||end.equals("xls")){
		// type = "application/vnd.ms-excel";
		// }
		else {
			// /*����޷�ֱ�Ӵ򿪣����������б���û�ѡ�� */
			type = "*/*";
		}
		return type;
	}

}
